package com.example.mvvmrxjavaokhttpretrofit.base;

import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import android.support.annotation.NonNull;


import com.example.mvvmrxjavaokhttpretrofit.net.BaseResponse;
import com.example.mvvmrxjavaokhttpretrofit.net.RdSubscriber;

import io.reactivex.Observer;

public abstract class BaseViewModel extends ViewModel {

    private MutableLiveData<BaseResponse<Object>> successLiveData = new MutableLiveData<>();
    private MutableLiveData<BaseResponse<Object>> errorLiveData = new MutableLiveData<>();

    @NonNull
    protected Observer createObserver(String requestType) {
        return new RdSubscriber(requestType) {
            @Override
            protected void onSuccess(int responCode, String responType, Object data) {
                BaseViewModel.this.onSuccess(responCode, responType, data);
            }

            @Override
            protected void onFail(int responCode, String responType, String message, Object data) {
                BaseViewModel.this.onFail(responCode, responType, message, data);
            }

        };
    }

    protected void onSuccess(int responCode, String responType, Object data) {
        BaseResponse<Object> successData = new BaseResponse<>();
        successData.setCode(responCode);
        successData.setData(data);
        successData.setRepType(responType);
        successLiveData.setValue(successData);
    }


    protected void onFail(int responCode, String responType, String message, Object data) {
        BaseResponse<Object> errorData = new BaseResponse<>();
        errorData.setCode(responCode);
        errorData.setMsg(message);
        errorData.setRepType(responType);
        errorData.setData(data);
        errorLiveData.setValue(errorData);
    }


    public MutableLiveData<BaseResponse<Object>> getErrorLiveData() {
        return errorLiveData;
    }

    public MutableLiveData<BaseResponse<Object>> getSuccessLiveData() {
        return successLiveData;
    }

    protected void setiDatasListener(BaseModel baseModel) {
        baseModel.setiDatasListener(new IDatasListener() {
            @Override
            public void getSuccess(int responCode, String responType, Object data) {
                onSuccess(responCode, responType, data);
            }

            @Override
            public void getfaild(int responCode, String responType, String errorMessage, Object data) {
                onFail(responCode, responType, errorMessage, data);
            }
        });
    }

}
